var express = require('express');
var router = express.Router();
var fs=require('fs');
var{resolve} =require('path');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});
//检查是否已经登录，如果没有登录，则转到登录页面
router.get('/checklogin',(req,res)=>{
  let cookie =req.cookies.username;
  if(!cookie){
    res.send('alert("请登录以后再操作！);location.href = "./login.html');
  }else{
   res.send('<script>windoe.userInfo="'+userInto+'";</script>');
  }
});
router.post('/login',(req,res)=>{
  let user =req.body.username;
  let pass =req .body.password;
  let fsuser = resolve(__dirname,'../public/data/user.json');


  let users = JSON.parse(fs.readFileSync(fsuser).toString('utf-8'));
  for(var i=0;i<users.length;i++){
    if(users[i].username === user&&users[i].password===pass){
      // res.cookie('userName',user ,{
      //   httpOnly:true,
      //   maxAge:30000
      // });
      req.session.userInfo=user;
      res.send({
        code:0,
        msg:'ok'
      });
      break;
    }
    if(i===users.length){
      res.send({
        code:1,
        msg:'error'
      });
    }
  }
  res.end();
});
module.exports = router;
